/**
 * Copyright (c) 2015 Sohu. All Rights Reserved
 */
package org.md5;

import java.util.Random;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.log4j.Logger;
import org.junit.Test;

/**
 * <p>
 * Description: 测试Md5盐加密
 * </p>
 * 
 * @author majintao
 * @version 1.0
 * @Date 2015年7月7日
 */
public class SaltMd5 {

    Logger log = Logger.getLogger(SaltMd5.class);

    static final String B64T = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    static final String MD5_PREFIX = "$1$";

    @Test
    public void testSalt() {
        // 随机的UUID盐(经测试，UUID无法实现盐加密)
        /*
         * UUID uuid = UUID.randomUUID(); String salt = uuid.toString();
         * log.info("UUID：" + salt);
         */

        String salt = "daaec908-6aec-4833-96c8-17147738e9c9";

        // 待加密的密码
        String pwd = "souhuv56";

        log.info("待加密的密码：" + pwd);

        // md5盐加密
        String md5pwd = Md5Crypt.md5Crypt(pwd.getBytes(), MD5_PREFIX + salt);

        log.info("加密后的密码：" + md5pwd);

        if ("$1$daaec908$YyBrDDdxkHPzo1yKKtC5c.".equals(md5pwd)) {
            log.info("equal");
        } else {
            log.info("no-equal");
        }

    }

    @Test
    public void test2() {
        String pwd = "souhuv56";
        log.info("待加密的密码：" + pwd);
        String md5pwd = Md5Crypt.md5Crypt(pwd.getBytes());
        String md5pwd2 = Md5Crypt.md5Crypt(pwd.getBytes());
        
        if(md5pwd.equals(md5pwd2)) {
            log.info("equal");
        }else {
            System.out.println("第一次md5"+md5pwd);
            System.out.println("第二次md5"+md5pwd2);
            log.info("no-equal");
        }
    }
    
    @Test
    public void test3() {
        String pwd = "souhuv56";
        String md5pwd = DigestUtils.md5Hex(pwd);
        String md5pwd2 = DigestUtils.md5Hex(pwd);
        
        if(md5pwd.equals(md5pwd2)) {
            log.info("equal");
        }else {
            System.out.println("第一次md5"+md5pwd);
            System.out.println("第二次md5"+md5pwd2);
            log.info("no-equal");
        }
    }

    @Test
    public void test4() {
        // 随机的UUID盐值(保存数据库)
        UUID uuid = UUID.randomUUID(); 
        String saltPrefix = uuid.toString();
        //待加密密码
        String pwd = "sohuv56";
        //采用UUID+pwd一起加密
        String md5pwd = DigestUtils.md5Hex(saltPrefix+pwd);
        
        log.info(md5pwd);
    }
    
    public String getRandomSalt(int num) {
        final StringBuilder saltString = new StringBuilder();
        for (int i = 1; i <= num; i++) {
            saltString.append(B64T.charAt(new Random().nextInt(B64T.length())));
        }
        return saltString.toString();
    }
}
